<template>
  <el-card class="register-container">
    <h2>用户注册</h2>
    <el-form @submit.prevent="handleRegister" label-position="top">
      <el-form-item label="用户名">
        <el-input v-model="addUser.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="addUser.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input v-model="addUser.confirmPassword" placeholder="请再次输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
        <el-button type="text" @click="navigateToLogin">返回登录</el-button> <!-- 返回登录按钮 -->
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { sm3 } from 'sm-crypto';
import { resetReactive } from "@/utils/index";
import { userRegister } from "@/api/user";

const router = useRouter();

const addUser = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  smPassword: '',
})

const handleRegister = async () => {
  if (addUser.password !== addUser.confirmPassword) {
    ElMessage.error('两次密码输入不一致');
    return;
  }
  addUser.smPassword = sm3(addUser.password);
  const body = {
    username: addUser.username,
    password: addUser.smPassword
  }
  // 调用注册接口
  const response = await userRegister(body);
  resetReactive(addUser);//清空输入框
  if (response.data.success) {
    ElMessage.success('注册成功');
    await router.push('/login');  // 注册成功后跳转到登录页面
  } else {
    ElMessage.error('注册失败, ' + response.data.errorMessage);
  }
};

// 导航到登录页面
const navigateToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 150px auto;
  padding: 20px;
}
</style>